// pages/activityRegistration/activityRegistration.js
const app = getApp()
const qiniu = require("../../utils/qiniu.min.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orgId: "",
    name: "",
    tel: "",
    turnover: "",
    num: 0,
    notes: "",
    imgArr: [],
    upfilelist: [],
    joinList: [],
    timeShow: false,
    initDate: "",
    birth: "",
    inputBlur:true,
  },
  //设置数据
  toggle: function (type, val) {
    this.setData({
      [type]: val
    });
  },
  setName(e) {
    this.toggle("name", e.detail.value.trim())
  },
  setTel(e) {
    this.toggle("tel", e.detail.value.trim())
  },
  setFieldContent(e) {
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var temp_str = 'joinList[' + index + '].fieldContent';
    var temp_length = 'joinList[' + index + '].length';
    this.setData({
      [temp_str]: e.detail.value.trim(),
      [temp_length]: e.detail.value.trim().length,
    })
  },
  hiddenTextarea(){
    this.toggle("inputBlur", true);
  },
  showTextarea() {
    this.toggle("inputBlur", false);
    this.toggle("focus", true);
  },
  //获取加入项
  getJoinInfo() {
    app.req({
      url: "orgmini/field/list",
      method: "POST",
      data: {
        orgId: this.data.orgId
      },
      success: ((res) => {
        // console.log(res,this)
        if (res.code == 200) {
          this.toggle("joinList", res.data)
          for (var item of this.data.joinList) {
            // if (item.fieldName == 3 && item.isChoose == 1) {
            //   item.fieldContent = ""; 
            // }
            if (item.fieldName == "备注" && item.isChoose == 1) {
              item.length = 0;
            }
            if (item.dataType == 1 && item.isChoose == 1) {
              item.imgArr = [];
            }
          }
        }
      })
    })
  },
  //身份证照片
  posterimg() {
    var that = this;
    if (that.data.imgArr.length >= 3) {
      wx.showToast({
        title: '最多只能上传3张图片',
        icon: 'none',
        duration: 2000
      })
    } else {
      app.getQiNiuToken(function (res) {
        var countnum = 3 - that.data.imgArr.length
        var qiniuconfig = res;
        let timestamp = new Date().getTime();
        wx.chooseImage({
          count: countnum,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: function (res) {
            const filepathArray = res.tempFilePaths
            for (let i = 0; i < filepathArray.length; i++) {
              qiniu.upload(filepathArray[i], res => {
                that.setData({
                  posterUrl: that.data.imgArr.concat([res.imageURL]),
                })
                that.toggle('imgArr', that.data.posterUrl)
                
              }, (error) => {
                // console.log('error' + error)
              }, {
                  uploadURL: 'https://upload.qiniup.com',
                  region: 'ECN',
                  domain: qiniuconfig.qiniuDomain,
                  uptoken: qiniuconfig.upToken,
                  key: timestamp + '.png',
                })
            }
          }
        })
      });
    }
  },
  delete: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.remove(that.data.imgArr, that.data.imgArr[index]);
    that.setData({
      posterUrl: that.data.imgArr
    });
    that.toggle('imgArr', that.data.posterUrl);
  },
  //删除元素
  remove: function (array, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == val) {
        array.splice(i, 1);
      }
    }
  },
  // 选择生日
  setBirthday(e) {
    // var item = e.currentTarget.dataset.item
    var M = (new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1);
    var now = new Date().getFullYear() + "-" + M + "-" + new Date().getDate();
    this.setData({
      initDate: this.data.birth,
    })
    if (this.data.birth){
      this.toggle("initDate", this.data.birth)
    }else{
      this.toggle("initDate", now)
    }
    this.setData({
      timeShow: true,
    })
  },
  // 设置生日
  setBirth: function (e) {
    console.log(e);
    console.log('日期类型：' + e.detail.dateType)
    // console.log('是否显示年份：' + e.detail.showYear)
    console.log('日期字符串：' + e.detail.dateStr)
    this.toggle("birth", e.detail.dateStr)
  },
  // 选择附件
  choosefilefun() {
    var that = this;
    if (that.data.upfilelist.length >= 5) {
      wx.showToast({
        title: '最多只能上传5份附件',
        icon: 'none',
        duration: 2000
      })
    } else {
      app.getQiNiuToken(function (res) {
        var countnum = 5 - that.data.upfilelist.length
        var qiniuconfig = res;
        wx.chooseMessageFile({
          count: countnum,
          type: 'file',
          success: function (res) {
            console.log(res);
            const tempFiles = res.tempFiles;
            for (let i = 0; i < tempFiles.length; i++) {
              qiniu.upload(tempFiles[i].path, res => {
                console.log(res)
                that.setData({
                  upfilelist: that.data.upfilelist.concat(res),
                })
              }, (error) => {
                // console.log('error' + error)
              }, {
                  uploadURL: 'https://upload.qiniup.com',
                  region: 'ECN',
                  domain: qiniuconfig.qiniuDomain,
                  uptoken: qiniuconfig.upToken,
                  key: tempFiles[i].name
                })
            }

          }
        })
      });
    }
  },
  //移除联系人
  removeFile(e) {
    this.removeArray(this.data.upfilelist, e.currentTarget.dataset.item);
  },
  //移除数组
  removeArray(_arr, _obj) {
    console.log(_arr, _obj)
    var length = _arr.length;
    for (var i = 0; i < length; i++) {
      if (_arr[i].hash == _obj.hash) {
        if (i == 0) {
          _arr.shift(); //删除并返回数组的第一个元素
          return this.setData({
            upfilelist: _arr
          });
        }
        else if (i == length - 1) {
          _arr.pop();  //删除并返回数组的最后一个元素
          return this.setData({
            upfilelist: _arr
          });
        }
        else {
          _arr.splice(i, 1); //删除下标为i的元素
          return this.setData({
            upfilelist: _arr
          });
        }
      }
    }
  },
  // 打开文档
  openFile(e) {
    var dataset = e.currentTarget.dataset;
    wx.downloadFile({
      url: dataset.url,
      success: function (res) {
        var filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          }
        })
      }
    })
  },
  //提交信息
  submit() {
    var that = this;
    var list = [];
    var phonePattern = /^((\d{3}-\d{8}|\d{4}-\d{7,8})|(1[3|4|5|6|7|8|9][0-9]{9}))$/;
    for (var item of this.data.joinList) {
      if (item.fieldName == '手机号' && item.isRequired == 1) {
        if (!this.data.tel) {
          wx.showToast({
            title: "请您前往个人资料页先设置手机号",
            icon: "none",
            duration: 3000
          })
          return
        } else {
          item.fieldContent = this.data.tel;
        }
      } else if (item.fieldName == '姓名') {
        if (this.data.name == '') {
          wx.showToast({
            title: "请输入姓名",
            icon: "none",
            duration: 3000
          })
          return
        } else {
          item.fieldContent = this.data.name;
        }
      } else if (item.fieldName == '生日'){
        var timeStape = new Date().getTime();
        var birthStamp = new Date(this.data.birth.replace(/-/g, "/")).getTime();
        if (birthStamp > timeStape){
          wx.showToast({
            title: "生日不能大于当前时间",
            icon: "none",
            duration: 3000
          })
          return
        }else{
          if (this.data.birth){
            item.fieldContent = this.data.birth + " 00:00:00";
          }else{
            item.fieldContent = "";
          }
        }
      }
      // else if (item.isChoose == 1 && item.dataType == 0 && item.fieldName != '姓名' && item.fieldName != '手机号'){
      //   if (!item.fieldContent){
      //     // wx.showToast({
      //     //   title: "请输入" + item.fieldName,
      //     //   icon: "none",
      //     //   duration: 3000
      //     // })
      //     // return
      //   }
      // } else if (item.isRequired == 1 && item.dataType == 1){
      //   if (this.data.imgArr.length == 0){
      //     wx.showToast({
      //       title: "请上传" + item.fieldName,
      //       icon: "none",
      //       duration: 3000
      //     })
      //     return
      //   }
      // } else if (item.isChoose == 1 && item.dataType == 2) {
      //   if (this.data.upfilelist.length == 0) {
      //     wx.showToast({
      //       title: "请上传" + item.fieldName,
      //       icon: "none",
      //       duration: 3000
      //     })
      //     return
      //   }
      // }
      item.fieldId = item.id;
      if (this.data.imgArr.length != 0 && item.dataType == 1 && item.isChoose == 1) {
        item.files = [];
        for (var i in this.data.imgArr) {
          item.files.push({
            fileType: 1,
            fileUrl: this.data.imgArr[i],
            fileName: this.data.imgArr[i].split('.com/')[1]
          })
        }
      }
      if (this.data.upfilelist.length != 0 && item.dataType == 2 && item.isChoose == 1) {
        item.files = [];
        for (var i in this.data.upfilelist) {
          item.files.push({
            fileType: 2,
            fileUrl: this.data.upfilelist[i].imageURL,
            fileName: this.data.upfilelist[i].key
          })
        }
      }
      if (item.isChoose ==1 ){
        list.push(item)
      }
    }
    console.log(this.data.joinList)
    app.req({
      url: "orgmini/org/joinOrg",
      method: "POST",
      data: {
        orgId: this.data.orgId,
        orgFieldContent: list
      },
      success(res) {
        if (res.code == 200) {
          wx.navigateBack({
            delta: 1
          })
          wx.showToast({
            title: "已提交组织审核，请耐心等待",
            duration: 2000,
            icon: 'none'
          })
          app.getRefresh(function (refresh) {
          }, '1')
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    this.toggle('orgId', options.orgId);
    this.getJoinInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo,
        name: userInfo.realName ? userInfo.realName : userInfo.nickName,
        tel: userInfo.telphone,
      })
      if (userInfo.birthday) {
        that.setData({
          birth: userInfo.birthday.substring(0, 10)
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})